<template>
  <div>

    <el-dropdown size="small" @command="userCommand">
      <span class="el-dropdown-link">
        {{currentName}}<i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="a">修改密码</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <el-dialog title="修改密码" :visible.sync="updatePwdDialogVisible" width="29%" @open="closeUpdateSelfPwdDialog" @close="closeUpdateSelfPwdDialog">
      <el-form ref="updatePwdRef" label-width="80px" label-position="left" :model="updatePwdForm" :rules="updatePwdRules">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="updatePwdForm.oldPassword" type="password" clearable></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="updatePwdForm.newPassword" type="password" @keyup.enter.native="updateSelfPwd" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSelfPwd">修改</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

export default {

  data () {
    // 账号校验规则
    let checkPassword = (rule, value, callback) => {
      this.$axios.post('/user/checkSelfPwd', { password: value })
        .then((res) => {
          if (!res.data.data) {
            callback(new Error('旧密码错误'))
          } else {
            callback()
          }
        })
    }
    return {
      //
      updatePwdDialogVisible: false,
      updatePwdForm: {
        oldPassword: '',
        newPassword: ''
      },
      // 用户模态校验
      updatePwdRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { max: 32, message: '旧密码最长 32 个字符', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { max: 32, message: '新密码最长 32 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 显示姓名、年份
    this.currentName = window.sessionStorage.getItem('realName')
  },
  methods: {
    // 用户下拉框操作
    userCommand (targetName) {
      switch (targetName) {
        case 'a':
          this.updatePwdDialogVisible = true
          break
        default:
          break
      }
    },
    // 个人密码修改提交
    async updateSelfPwd () {
      this.$refs.updatePwdRef.validate(async valid => {
        if (valid) {
          const { data } = await this.$axios.post('/user/updateSelfPwd', this.updatePwdForm)
          // 后续操作：弹窗、关模态
          this.$message.success(data.msg)
          this.updatePwdDialogVisible = false
        }
      })
    },
    // 关模态时重置表单重置表单
    closeUpdateSelfPwdDialog () {
      this.$refs.updatePwdRef.resetFields()
    }
  }
}
</script>
